<!doctype html>
<html>

  <head>
    <meta charset="utf-8">
    <title>待办详情</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <link href="../../../css/mui.min.css" rel="stylesheet" />
    <link href="../css/common.css" rel="stylesheet" />
    <link href="../css/iconfont.css" rel="stylesheet" />
    <style>
      .mui-btn, button, input[type=button], input[type=reset], input[type=submit] {
        padding: 6px 10px;
      }
      .mui-popover {
      				height: 90px;
              width: 200px;
      			}
    </style>
  </head>

  <body>
    <div class="container" id="container" v-cloak>
      <header class="mui-bar mui-bar-nav">
        <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
        <h1 class="mui-title">设备档案详情</h1>
        <a class="mui-pull-right iconfont icon-bianji mui-right-icon" href="#topPopover"> 操作</a>
      </header>
      <!--右上角弹出菜单-->
      <div id="topPopover" class="mui-popover">
        <div class="mui-popover-arrow"></div>
        <div class="mui-scroll-wrapper">
          <div class="mui-scroll">
            <ul class="mui-table-view">
              <li class="mui-table-view-cell" @click="offline()" v-if="!isOffline">
                <a href="javascript:;">离线存储</a>
              </li>
              <li class="mui-table-view-cell" @click="offline()" v-else><a href="#">重新离线</a>
              </li>
              <!-- <li class="mui-table-view-cell"><a href="#">数据提交</a>
              </li> -->
              <li class="mui-table-view-cell" @click="edit()"><a href="javascript:void(0);">编辑</a>
              </li>
            </ul>
          </div>
        </div>

      </div>
      <div class="mui-content bg-white" style="padding-bottom: 50px;">
        <div class="content-Title">
          <span class="titleB">功能位置编码</span>
        </div>
        <div class="content">
          <div class="item flex">
            <div class="text-grey">功能位置编码:</div>
            <div class="text-black">{{ detail.mdmCode }}</div>
          </div>
          <div class="item flex" v-if="detail.parentName">
            <div class="text-grey">上级设备:</div>
            <div class="text-black">{{ detail.parentName }}</div>
          </div>
        </div>
        <div class="content-Title">
          <span class="titleB">区域信息</span>
        </div>
        <div class="content">
          <div class="item flex">
            <div class="text-grey">所属区域:</div>
            <div class="text-black">{{ detail.areaNames }}</div>
          </div>
          <div class="item flex">
            <div class="text-grey">所属场站:</div>
            <div class="text-black">{{ detail.stationNames }}</div>
          </div>
          <div class="item flex">
            <div class="text-grey">所属项目:</div>
            <div class="text-black">{{ detail.projectNames }}</div>
          </div>
          <div class="item flex">
            <div class="text-grey">项目公司:</div>
            <div class="text-black">{{ detail.projectCompanyName }}</div>
          </div>
        </div>
        <div class="content-Title">
          <span class="titleB">设备信息</span>
        </div>
        <div class="content">
          <div class="item flex">
            <div class="text-grey">设备名称:</div>
            <div class="text-black">{{ detail.deviceName }}</div>
          </div>
          <div class="item flex">
            <div class="text-grey">设备型号:</div>
            <div class="text-black">{{ detail.sn }}</div>
          </div>
        </div>
        <div class="content-Title">
          <span class="titleB">属性信息</span>
        </div>
        <div class="content">
          <div class="item flex" key="domain.id" v-for="domain in propone">
            <div class="text-grey">{{domain.mdName}}:</div>
            <div class="text-black"><span class="rowContent" v-if="domain.mdPropType == 0">{{ domain.mdDictValueRemarks || (domain.value?domain.value:'无') }}</span></div>
            <div>
              <span class="form-subtext" v-if="domain.mdUnit">{{domain.mdUnit}}</span>
            </div>
            <div v-if="domain.mdPropType == 10" style="float: left;margin-right: 10px;">
              <span v-if="domain.attachmentPath">{{domain.attachmentName}}</span>
              <span v-else class="text-grey">未上传</span>
              <a href="javascript:void(0);" v-if="domain.attachmentPath" @click="open(domain)">预览</a></div>
          </div>
        </div>
		<div class="content-Title">
		  <span class="titleB">运行视图</span>
		</div>
		<div class="content">
		  <div class="item flex" key="domain.id" v-for="domain in proptwo">
		    <div class="text-grey">{{domain.mdName}}:</div>
		    <div class="text-black"><span class="rowContent" v-if="domain.mdPropType == 0">{{ domain.mdDictValueRemarks || (domain.value?domain.value:'无') }}</span></div>
		    <div>
		      <span class="form-subtext" v-if="domain.mdUnit">{{domain.mdUnit}}</span>
		    </div>
		    <div v-if="domain.mdPropType == 10" style="float: left;margin-right: 10px;">
		      <span v-if="domain.attachmentPath">{{domain.attachmentName}}</span>
		      <span v-else class="text-grey">未上传</span>
		      <a href="javascript:void(0);" v-if="domain.attachmentPath" @click="open(domain)">预览</a></div>
		  </div>
		</div>
		<div class="content-Title">
		  <span class="titleB">检修视图</span>
		</div>
		<div class="content">
		  <div class="item flex" key="domain.id" v-for="domain in propthree">
		    <div class="text-grey">{{domain.mdName}}:</div>
		    <div class="text-black"><span class="rowContent" v-if="domain.mdPropType == 0">{{ domain.mdDictValueRemarks || (domain.value?domain.value:'无') }}</span></div>
		    <div>
		      <span class="form-subtext" v-if="domain.mdUnit">{{domain.mdUnit}}</span>
		    </div>
		    <div v-if="domain.mdPropType == 10" style="float: left;margin-right: 10px;">
		      <span v-if="domain.attachmentPath">{{domain.attachmentName}}</span>
		      <span v-else class="text-grey">未上传</span>
		      <a href="javascript:void(0);" v-if="domain.attachmentPath" @click="open(domain)">预览</a></div>
		  </div>
		</div>
		<div class="content-Title">
		  <span class="titleB">其他视图</span>
		</div>
		<div class="content">
		  <div class="item flex" key="domain.id" v-for="domain in propfour">
		    <div class="text-grey">{{domain.mdName}}:</div>
		    <div class="text-black"><span class="rowContent" v-if="domain.mdPropType == 0">{{ domain.mdDictValueRemarks || (domain.value?domain.value:'无') }}</span></div>
		    <div>
		      <span class="form-subtext" v-if="domain.mdUnit">{{domain.mdUnit}}</span>
		    </div>
		    <div v-if="domain.mdPropType == 10" style="float: left;margin-right: 10px;">
		      <span v-if="domain.attachmentPath">{{domain.attachmentName}}</span>
		      <span v-else class="text-grey">未上传</span>
		      <a href="javascript:void(0);" v-if="domain.attachmentPath" @click="open(domain)">预览</a></div>
		  </div>
		</div>
      </div>
      <div class="footer fixed shadow" style="padding:10px 10px">
        <div class="flex justify-between">
          <button type="button" class="mui-btn mui-btn-primary" @click="view()">子设备</button>
          <button type="button" class="mui-btn mui-btn-primary" @click="system()">外部系统记录</button>
          <!-- <button type="button" class="mui-btn mui-btn-primary">巡检记录</button> -->
          <button type="button" class="mui-btn mui-btn-primary" @click="record()">操作记录</button>
          <!-- <button type="button" class="mui-btn mui-btn-primary">编辑</button> -->
        </div>
      </div>
      <div class="popUp" id="popUp" style="display: none;">
        <form action="" class="popUpContent">
          <div class="item flex">
            <div class="label">审批：</div>
            <div class="flex">
              <div class="mui-input-row mui-radio mui-left">
                <label>通过</label>
                <input name="radio1" type="radio">
              </div>
              <div class="mui-input-row mui-radio mui-left">
                <label>未通过</label>
                <input name="radio1" type="radio" checked>
              </div>
            </div>
          </div>
          <div class="item flex">
            <div class="label">意见：</div>
            <div class="flex-sub ">
              <textarea id="textarea" rows="5" placeholder="多行文本框"></textarea>
            </div>
          </div>
          <div class="item flex">
            <div class="label"></div>
            <div class="flex-sub flex">
              <button type="button" class="mui-btn mui-btn-primary mui-btn-outlined flex-sub">取消</button>
              <button type="button" class="mui-btn mui-btn-primary flex-sub">确认</button>
            </div>
          </div>
        </form>
      </div>
    </div>

  </body>
  <script src="../../../js/mui.min.js"></script>
  <script src="../../../js/vue.js"></script>
  <script src="../../../js/jquery-1.7.2.min.js"></script>
  <script src="../js/mkeyplus.base.js"></script>
  <script src="../js/sqlite.js"></script>
  <script type="text/javascript">
    mui.init()
    var mask = null;
    var detailVm = null;
    var cv = null; // 当前webview
    var pageId = ""; //获取详情id
    var databaseName = "offlineFiles"; //定义表的名字
    var bdName = "files"; //数据库的名字
    var PName = "offlinePeople"; //责任人的名字
    var dtask = null;
    var queue = new Queue();
    mui.plusReady(function() {
      cv = plus.webview.currentWebview();
      pageId = cv.pageId || '';
      console.log(pageId)
      detailVm.getDetail(pageId);
      // detailVm.people(pageId);
      if (!validBdOpen(bdName)) {
        createDb(bdName)
      }
      var baseSql = 'create table if not exists ' + databaseName +
        '("mainId" CHAR(100),"id" CHAR(100),"parentId" CHAR(100),"deviceName" CHAR(1000),"mdmCode" CHAR(100),"stationNames" CHAR(1000),"mdmMainFlag" text,"isEdit" INT(100),"isComplete" INT(100),"detail" text)';
      executeListSQL(bdName, baseSql); //创建表
      selectListSQL(bdName, "select " + selectName + " from " + databaseName + " WHERE id ='" + pageId + "'", function(data) {
        if (data.length > 0) {
          detailVm.isOffline = true
        }
      });
    })
    detailVm = new Vue({
      el: "#container",
      data: {
        detail: {
          model: {
            propDatas: []
          },
        },
		propone:[],
		proptwo:[],
		propthree:[],
		propfour:[],
        isOffline: false,
        peopleList: [],
        ChildDocuments: [],

      },
      created: function() {},
      methods: {
        people(pageId) {
          var baseSql = 'create table if not exists ' + PName +
            '("id" CHAR(100),"type" CHAR(100),"documentId" CHAR(1000),"userId" CHAR(100),"username" CHAR(100),"phone" CHAR(100),"employeeNo" text,"realname" text,"deptName" text,"source" text)';
          executeListSQL(bdName, baseSql); //创建责任人表
          var that = this;
          mui.baseApp.httpRequst("/api/metadataDocument/getAllDocumentsManager", {
            copyFlag: false,
            childModelFlag: true,
            id: pageId
          }, function(data) {
            // console.log('责任人+++++' + JSON.stringify(data))
            that.peopleList = data;
          }, function() {
            plus.nativeUI.closeWaiting();
            console.log("获取数据失败");
          })
        },
        offlinePeople() {
          var that = this;
          that.peopleList.forEach(function(item, index) {
            selectListSQL(bdName, "select * from " + PName + " WHERE employeeNo='" + item.employeeNo + "'",
              function(data) {
                console.log('查出数据表数据' + data.length);
                if (data.length > 0) {
                  var baseSql = "UPDATE " + PName + " SET username ='" + item.username + "',deptName ='" +
                    item.deptName + "',type= '" + item.type + "',realname = '" + item.realname + "',source='" +
                    item.source + "',documentId='" + item.documentId + "'  WHERE employeeNo ='" + item.employeeNo + "'";
                  selectListSQL(bdName, baseSql, function(data) {});
                } else {
                  // '("id" CHAR(100),"type" CHAR(100),"documentId" CHAR(1000),"userId" CHAR(100),"username" CHAR(100),"phone" CHAR(100),"employeeNo" text,"realname" text,"deptName" text,"source" text)';
                  var sql = "insert into " + PName + " values('" + item.id + "','" + item.type + "','" + item
                    .documentId + "','" + item.userId + "','" + item.username + "','" + item.phone + "','" +
                    item.employeeNo + "','" + item.realname + "','" + item.deptName + "','" + item.source +
                    "')";
                  executeListSQL(bdName, sql);

                }

              });
          })

        },
        offline() { //离线存储
          mui(".mui-popover").popover("toggle");
          
          // plus.nativeUI.showWaiting('存储中...');
          var that = this;
           batchOffline([that.detail],[pageId]);
           that.isOffline=true;
          // if (that.ChildDocuments.length === 0) {
          //   plus.nativeUI.closeWaiting()
          //   return;
          // }
          // var length=that.ChildDocuments.length;
          // that.ChildDocuments.forEach(function(data, index) {
          //   that.offlineData(data,length,index);
          // })
          // hotPotato();//下载文件
          // that.offlinePeople(); //离线责任人
        },
        offlineData(item, length, index) { //存储子设备
          var that = this;
          console.log(length)
          selectListSQL(bdName, "select " + selectName + " from " + databaseName + " WHERE id ='" + item.id + "'", function(data) {
            // console.log('查出数据表数据'+JSON.stringify(data));
            if (data.length > 0) {
               var baseSql = "UPDATE " + databaseName + " SET detail ='" + JSON.stringify(item) + "' WHERE id ='" + item.id + "'";
              if(that.detail.model.mdmMainFlag){//判断当前是否是主设备
                baseSql = "UPDATE " + databaseName + " SET detail ='" + JSON.stringify(item) + "',mainId='"+that.detail.id+"' WHERE id ='" + item.id + "'";
              }
              selectListSQL(bdName, baseSql, function(data) {
                if (length - 1 === index) {
                   // selectListSQL(bdName, "select " + selectName + " from " + databaseName + " WHERE id ='" + that.pageId + "'", function(data) {
                     var baseSql = "UPDATE " + databaseName + " SET isComplete = 1 WHERE id ='" + that.pageId + "'";
                     executeListSQL(bdName, baseSql);  
                   // })
                  that.isOffline=true;
                  plus.nativeUI.closeWaiting();
                }
              });
            } else {
              var sql = "insert into " + databaseName + " values('" + that.detail.id + "','" + item.id + "','" +
                item.parentId + "','" + item.deviceName + "','" + item.mdmCode + "','" + item.stationNames +
                "','" + item.model.mdmMainFlag + "',0,0,'" + JSON.stringify(item) + "')";
              executeListSQL(bdName, sql);
              if (length - 1 === index) {
                // selectListSQL(bdName, "select " + selectName + " from " + databaseName + " WHERE id ='" + that.pageId + "'", function(data) {
                  var baseSql = "UPDATE " + databaseName + " SET isComplete = 1 WHERE id ='" + that.pageId + "'";
                  executeListSQL(bdName, baseSql);  
                // })
                that.isOffline=true;
                plus.nativeUI.closeWaiting();
              }
            }
          });
        },
        child() {
          var that = this;
          mui.baseApp.httpRequst("/api/metadataDocument/getAllChildDocuments", {
            isTree: false,
            parentId: that.detail.id
          }, function(ChildDocuments) {
            that.ChildDocuments = ChildDocuments
            console.log(that.ChildDocuments.length)
            ChildDocuments.forEach(function(data, index) {
              let {
                childDocuments,
                model
              } = data;
              let {
                childModels,
                propDatas
              } = model;
              if (propDatas) {
                var enumNames = [];
                propDatas.forEach(propData => {
                  if (propData.mdPropType == 10 && propData.attachmentPath) {
                    queue.enqueue(propData); //初始化，进入队列
                  }
                });
              }
            })
            plus.nativeUI.closeWaiting();
          }, function() {
            plus.nativeUI.closeWaiting();
            console.log("获取数据失败");
          })
        },
        //打开子设备
        view: function() {
          mui.openWindow({
            url: '../file/fileChildren.html',
            id: '../file/fileChildren.html',
            createNew: true, //是否重复创建同样id的webview，默认为false:不重复创建，直接显示
            extras: {
              pageId: pageId
            }
          })
        },
        //操作记录
        record: function() {
          mui.openWindow({
            url: '../file/record.html',
            id: '../file/record.html',
            extras: {
              pageId: pageId
            }
          })
        },
        //编辑
        edit: function() {
          mui(".mui-popover").popover("toggle");
          mui.openWindow({
            url: '../file/fileEdit.html',
            id: '../file/fileEdit.html',
            createNew: true, //是否重复创建同样id的webview，默认为false:不重复创建，直接显示
            extras: {
              pageId: pageId
            }
          })
        },
        system:function(){
          var that=this;
          mui.openWindow({
            url: '../file/system.html',
            id: '../file/system.html',
            createNew: true, //是否重复创建同样id的webview，默认为false:不重复创建，直接显示
            extras: {
              mdmCode: that.detail.mdmCode
            }
          })
        },
        //获取详情
        getDetail: function(pageId) {
          plus.nativeUI.showWaiting('加载中...');
          var that = this
          mui.baseApp.httpRequst("/api/metadataDocument/info", {
            copyFlag: false,
            childModelFlag: true,
            id: pageId
          }, function(data) {
            let {
              childDocuments,
              model
            } = data;
            let {
              childModels,
              propDatas
            } = model;
            if (childDocuments && childModels) {
              var childModelsNew = childModels.map((childModel, i) => {
                var filterDoc = childDocuments.filter(
                  element => element.metadataModelId == childModel.id
                );
                return { ...childModel,
                  childDocuments: filterDoc
                };
              });
              data.model.childModels = childModelsNew;
            }
            if (propDatas) {
              var enumNames = [];
              propDatas.forEach(propData => {
                if (propData.mdJavaType == "Enum" && propData.mdDictName) {
                  enumNames.push(propData.mdDictName);
                }
              });
              if (enumNames.length) {
                mui.baseApp.httpRequst("/api/dictItem/map", {
                  dictName: enumNames.join(","),
                  page: 0,
                  size: 9999
                }, function(resMap) {
                  that.dictDatas = resMap;
                  data.model.propDatas = propDatas.map(propData => {
                    if (propData.mdJavaType == "Enum" && propData.mdDictName) {
                      var dictList = resMap[propData.mdDictName];
                      if (dictList && propData.value) {
                        for (var i of dictList) {
                          // console.log('mdDictValueRemarks', i, propData.value)
                          if (i.value == propData.value) {
                            propData.mdDictValueRemarks = i.label;
                            break;
                          }
                        }
                      }
                    }
                    return propData;
                  });
                  that.detail = data;
                }, function() {
                  console.log("获取数据失败");
                })
              } else {
                data.model.propDatas = propDatas.map((propData, i) => {
                  // console.log('propData', self.dictDatas, propData.mdDictName)
                  return {
                    ...propData,
                    dictDatas: propData.mdJavaType == "Enum" && propData.mdDictName ?
                      self.dictDatas[propData.mdDictName] : []
                  };
                });
              }
            }
            plus.nativeUI.closeWaiting();
            // console.log('子设备' + JSON.stringify(data))
            that.detail = data
			
			var _propData = that.detail.model.propDatas;
			for (var i = 0; i < _propData.length; i++) {
				var sort = _propData[i].metadataRelation.mdPropSort;
				if(sort){
					if(~sort.indexOf('0')){
						that.propone.push(_propData[i])
					}
					if(~sort.indexOf('1')){
						that.proptwo.push(_propData[i])
					}
					if(~sort.indexOf('2')){
						that.propthree.push(_propData[i])
					}
					if(~sort.indexOf('3')){
						that.propfour.push(_propData[i])
					}
				}else{
					that.propone.push(_propData[i])
				}
				
			}
            // that.child();
          }, function() {
            plus.nativeUI.closeWaiting();
            console.log("获取数据失败");
          })
        },
        //打开附件
        open: function(item) {
          var FileSystemURL = "_downloads/"+ item.id + "/" + item.attachmentName;
          plus.io.resolveLocalFileSystemURL(FileSystemURL, function() {
            console.log('文件已存在')
            plus.runtime.openFile(FileSystemURL, {}, function(e) {
              alert('打开失败');
            });
          }, function() {
            console.log("未找到文件")
            var dtask = plus.downloader.createDownload(item.attachmentPath, {filename:"_downloads/" + item.id + "/" + item.attachmentName}, function(
              d, status) {
              if (status == 200) {
                var fileUrl = d.filename;
               plus.runtime.openFile(fileUrl, {}, function(e) {
                 alert('打开失败');
               });
              } else {
                alert("Download failed: " + status);
              }
            });
            dtask.start();
          });
          // var dtask = plus.downloader.createDownload(url, {}, function(d, status) {
          //   if (status == 200) {
          // var fileUrl = url;
          // console.log(fileUrl)
          // var fileUrl = "_downloads/"+ item.id + "/" + item.attachmentName;
          // plus.runtime.openFile(fileUrl, {}, function(e) {
          //   alert('打开失败');
          // });
          //   } else {
          //     alert("Download failed: " + status);
          //   }
          // });
          // dtask.start();
        }
      },

    })
    window.addEventListener("update", function(e) {
      console.log('更新数据');
      detailVm.getDetail(pageId);
      if (detailVm.isOffline) {
        detailVm.offline(); //更新离线数据
      }
    });
    mask = mui.createMask(function() {
      $('#popUp').hide();
    });

    function Queue() {
      var items = [];
      this.enqueue = function(ele) {
        items.push(ele);
      }; //入队
      this.dequeue = function() {
        return items.shift();
      }; //出队
      this.front = function() {
        return items[0];
      }; //查看队头元素
      this.isEmpty = function() {
        return items.length === 0;
      }; //判断队列是否为空
      this.size = function() {
        return items.length;
      }; //队列大小
      this.clear = function() {
        items = [];
      }; //清空队列
      this.print = function() {
        console.log(items.toString());
      }; //打印队列
    }

    function hotPotato() { 
      console.log(queue.size())
      var eliminated; 
      while (!queue.isEmpty()) { 
        eliminated = queue.dequeue(); 
        dTask(eliminated)
        console.log(eliminated + '被淘汰');
      }
    }



    function dTask(item) {
      var isUrl = false;
      var FileSystemURL = "_downloads/"+ item.id + "/" + item.attachmentName;
      plus.io.resolveLocalFileSystemURL(FileSystemURL, function() {
        console.log('一下载');
        hotPotato();
      }, function() {
        var dtask = plus.downloader.createDownload(propData.attachmentPath, {filename:"_downloads/" + propData.id + "/" + propData.attachmentName}, function(
          d, status) {
          if (status == 200) {
            console.log("下载成功")
            hotPotato();  
          } else {
            mui.toast(propData.attachmentName+'下载失败')
            hotPotato();
          }
        });
        dtask.start();
      });
    }
  </script>
</html>
